from __future__ import absolute_import, unicode_literals

import os

from celery import Celery
from celery.schedules import crontab
import django

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'settings.local')
django.setup()

app = Celery('recruitment')

app.config_from_object('django.conf:settings', namespace='CELERY')  # namespace表示我们所有的配置都以大写的celery作为前缀

app.autodiscover_tasks()

from recruitment.tasks import add  # 必须显示导入才能正确注册

# 手动添加定时任务
app.conf.beat_schedule = {
    'add-every-10-seconds': {
        'task': 'recruitment.tasks.add',  # add 方法必须显示的引入进来 不然执行不了会报错
        'schedule': 10.0,
        'args': (16, 4,)
    }
}


# celery应用配置加载完后设置定时任务
@app.on_after_configure.connect
def setup_periodic_tasks(sender, **kwargs):
    sender.add_periodic_task(10.0, test.s('hello'), name='hello every 10')

    sender.add_periodic_task(30.0, test.s('word'), expires=10)

    sender.add_periodic_task(
        crontab(hour=7, minute=30, day_of_week=1),
        test.s('Happy Mondays!'),
    )


# 项目启动时动态的添加定时任务
import json
from django_celery_beat.models import PeriodicTask, IntervalSchedule

# 先创建定时策略
schedule, created = IntervalSchedule.objects.get_or_create(every=10, period=IntervalSchedule.SECONDS, )

# 在创建任务
task = PeriodicTask.objects.get_or_create(interval=schedule, name='say hello everyone', task='recruitment.celery.test',
                                          args=json.dumps(['welcome', 'hello', 'everyone']))


@app.task(bind=True)
def debug_task(self):
    print('Request: {0!r}'.format(self.request))


@app.task
def test(arg):
    print(arg)
